package com.yunduo.controller;

import com.yunduo.common.JwtUtils;
import com.yunduo.common.RetunData.CommonReturn;
import com.yunduo.common.RetunData.statuscode.ResultStatus;
import com.yunduo.common.RetunData.statuscode.impl.ResultCode;
import com.yunduo.common.RetunData.statuscode.impl.ServerCode;
import com.yunduo.common.RetunData.statuscode.impl.UserCode;
import com.yunduo.common.YunDuoUtils;
import com.yunduo.entity.User;
import com.yunduo.entity.vo.LoginUser;
import com.yunduo.schedule.TimerTask.UserOutLoginTask;
import com.yunduo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * 安全控制类
 */
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;

    //登录认证
    @PostMapping("/login")
    public CommonReturn login(@RequestBody @Valid LoginUser user){
        User userInfo = userService.getUserByName(user.getName());
        //用户是否存在
        if(userInfo == null){
            return CommonReturn.ERROR(UserCode.USER_ACCOUNT_ISNOT);
        }
        if (userInfo.getIsDeleted()) {
            return CommonReturn.ERROR(UserCode.USER_IS_DELETE);
        }
        //封装token
        AuthenticationToken authToken = new UsernamePasswordToken(user.getName(), user.getPassword());
        //验证登录
        ResultStatus result = YunDuoUtils.login(authToken);
        //登录成功 封装返回Token
        if(UserCode.USER_LOGIN_SUCCESS.getInfo().equals(result.getInfo())){
            String userId = userService.getUserByName(user.getName()).getId();
            String accessToken = JwtUtils.getJwtToken(userId,user.getName(),user.getPassword());
            return CommonReturn.SUCCESS(UserCode.USER_LOGIN_SUCCESS).setData("access_token",accessToken);
        }
        return CommonReturn.ERROR(UserCode.USER_ACCOUNT_ISNOT);
    }

    //用户退出 删除用户
    @PostMapping("/logout")
    public CommonReturn logout(HttpServletRequest request) {
        Subject lvSubject= SecurityUtils.getSubject();
        lvSubject.logout();
        String name = JwtUtils.getDataByJwtToken(request).getName();
        redisTemplate.opsForSet().remove(ServerCode.ONLINE_ACCOUNT_TOTAL.getInfo(),name);
        return CommonReturn.SUCCESS(UserCode.USER_LOGIN_OUT);
    }
}
